// pages/institutions/institutions.js
import urls from '../../utils/urls';
import loginFn from '../../utils/login';
var app = getApp();

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		canEdit: false,
		schoolId: 0, //机构id
		schoolName: '', //机构名称
		courseId: 0, //课程ID
		courseName: '', //课程名称
		allpickers: {}, //所有课程分类
		courseMain: [], //课程类别
		allcourseMain: [], //所有课程
		types: ['培训机构', '机构'],
		typeIndex: [0, 0], //默认课程类型
		coverimg: '/img/upload.png', //机构logo图片
		classImg: [], //机构图片
		coverImgId: '', //封面照片
		classImages: [], //封面照片
		coursePointTxt: '', //课程特色
		coursePoints: [], //所有课程特点
		selcoursePoint: false, //选择课程特点
		minAge: '', //最小年龄
		maxAge: '', //最大年龄
		price: '', //现价
		summary: '', //简介
		minAge: '', //最小年龄
		maxAge: '', //最大年龄
		price: '', //现价
		oldPrice: '', //原价
		testClass: false, //体验
		courseBaseIdx: 0, //课程适用基础
		totalClassHours: '', //总课时
		duration: '', //课程时长
		startTime: '00:00', //课程开始时间
		endTime: '00:00', //课程结束时间
		allteacher: [], //所有教师
		selteacher: false, //选择教师
		teachers: '', //教师
		teacherArr: [], //选中的教师
		weeks: [ //所有教师选项
			{
				teacherId: '1',
				teacherName: '星期一',
				checked: false
			},
			{
				teacherId: '2',
				teacherName: '星期二',
				checked: false
			},
			{
				teacherId: '3',
				teacherName: '星期三',
				checked: false
			},
			{
				teacherId: '4',
				teacherName: '星期四',
				checked: false
			},
			{
				teacherId: '5',
				teacherName: '星期五',
				checked: false
			},
			{
				teacherId: '6',
				teacherName: '星期六',
				checked: false
			},
			{
				teacherId: '7',
				teacherName: '星期日',
				checked: false
			}
		],
		weekArr: [], //选中的星期
		week: '', //默认星期几
		selweek: false, //选择星期
		coursePeopleIdx: 0, //上课人数
		regionItem: '全部', //地区顶部设置
		region: ['广东省', '广州市', '海珠区'], //默认地区
		approachaIdx: 0, //默认办学模式
		approachas: ['民办学校', '公办学校'], //办学形式
		sizesIdx: 0, //默认学校规模
		sizes: ['连锁', '个体'], //学校规模
		majorIdx: 0, //默认专业方向
		major: ['外语', '游泳', '篮球'], //专业方向
		time: '12:01',
		primarySize: 'default', //提交按钮样式
		disabled: false,
		plain: false,
		loading: false,
		btnTxt: '提交',
		btnType: 'primary',
		times: [
			['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18',
				'19', '20', '21', '22', '23'
			],
			['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55']
		]
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log('options:',options);
		var that = this;
		var lognInfo = loginFn();
		if (options.cousrseId != undefined) {
			loginInfo.schoolId = options.schoolId
			that.setData({
				schoolId: options.schoolId,
			})
		}

		if(options.schoolName) {
			this.setData({
				schoolName: options.schoolName
			});
		}

		if(options.type && options.type == 'edit') {
			this.canEdit();
		}

			that.setData({
				schoolId: options.schoolId
			});

			lognInfo.schoolId = options.schoolId;
		

		wx.request({
			url: urls.addClasstype+"?isTui=1",
			data: lognInfo,
			success: function(res) {
				console.log(res)
				that.setData({
					allcourseMain: res.data.data.courseMain,
					allteacher: res.data.data.courseTeacher,
					coursePoints: res.data.data.coursePoint,
				})

				var all = res.data.data;
				var arr = [];
				arr.push(all.courseMain)
				if (all.courseMain[0].sub) {
					arr.push(all.courseMain[0].sub)
				} else {
					arr[1] = []
				}
				that.setData({
					courseMain: arr,
					allpickers: res.data.data
				})
				//判断是否是编辑
				that.editFn(options)
			}
		})

	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	// 函数
	bindTypeChange: function(e) { //选择机构类别
		console.log('picker account 发生选择改变，携带值为', e);
		this.setData({
			typeIndex: e.detail.value
		})
	},
	bindcolumnchange: function(e) { //改变课程类别选项
		console.log(e)
		if (e.detail.column == '0') {
			var all = this.data.courseMain;
			if (this.data.courseMain[0][e.detail.value].sub) {
				all[1] = this.data.courseMain[0][e.detail.value].sub;
			} else {
				all[1] = []
			};
			console.log(all)
			this.setData({
				courseMain: all
			})
		};
	},
	choosecoverImg: function(e) { //选择封面图片
		var that = this;
		wx.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				// tempFilePath可以作为img标签的src属性显示图片
				var tempFilePaths = res.tempFilePaths;
				app.uploadImage(tempFilePaths[0], (res) => {
					if(res.code == 1) {
						that.setData({
							coverimg: tempFilePaths[0],
							coverImgId: res.data.imageFileId
						})
					} else {
						app.alert(res.msg);
					}
				})
			}
		})
	},
	chooseclassImg: function(e) { //选择机构图片
		var that = this;
		wx.chooseImage({
			count: 9,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				// tempFilePath可以作为img标签的src属性显示图片
				var tempFilePaths = res.tempFilePaths
				for (var i = 0; i < tempFilePaths.length; i++) {
					that.uploadFn(tempFilePaths[i])
				}
			}
		})
	},

	closeimg: function(e) { //删除图片
		console.log(e)
		var insImgs = this.data.classImg
		var classImages = this.data.classImages
		insImgs.splice(e.currentTarget.dataset.idx, 1)
		classImages.splice(e.currentTarget.dataset.idx, 1)
		this.setData({
			insImgs: insImgs,
			classImages: classImages
		})
	},
	uploadFn(tempFilePaths) { //上传图片
		var that = this;
		app.uploadImage(tempFilePaths, (res) => {
			if(res.code == 1) {
				var teacherImages = that.data.classImages;
				teacherImages.push(res.data.imageFileId)
				var insImgs = that.data.classImg;
				insImgs.push(tempFilePaths)

				that.setData({
					classImg: insImgs,
					classImages: teacherImages
				})
			} else {
				app.alert(res.msg);
			}
		})
	},
	startTimeChange: function(e) { //营业开始时间
		var start = this.data.times[0][e.detail.value[0]] + ':' + this.data.times[1][e.detail.value[1]]
		console.log(start)
		this.setData({
			startTime: start
		})
	},
	endTimeChange: function(e) { //营业结束时间
		var endTime = this.data.times[0][e.detail.value[0]] + ':' + this.data.times[1][e.detail.value[1]]
		this.setData({
			endTime: endTime
		})
	},
	courseBaseChange(e) { //选择地区
		this.setData({
			courseBaseIdx: e.detail.value
		})
	},
	coursePeopleChange: function(e) { //课堂人数
		this.setData({
			coursePeopleIdx: e.detail.value
		})
		console.log(this.data.coursePeopleIdx)
	},
	teacherChange: function(e) { //选择教师
		this.setData({
			selteacher: true
		})
	},
	checkAuth: function(e) { //选中返回
		console.log(e)
		if (e.detail) {
			var arr = '';
			var allteachers = this.data.allteacher
			//去除原来选项
			for (var j = 0; j < allteachers.length; j++) {
				allteachers[j].checked = false;
			}
			//更新选项
			for (var k = 0; k < e.detail.length; k++) {
				for (var i = 0; i < allteachers.length; i++) {
					if (e.detail[k] == allteachers[i].teacherId) {
						allteachers[i].checked = true;
						if (k == e.detail.length - 1) {
							arr += allteachers[i].teacherName
						} else {
							arr += allteachers[i].teacherName + '、'
						}
					};
				}
			};
			this.setData({
				selteacher: false,
				teachers: arr,
				teacherArr: e.detail,
				allteacher: allteachers
			})
		} else {
			this.setData({
				selteacher: false
			})
		}

	},
	weekChange: function(e) { //选择星期
		this.setData({
			selweek: true
		})
	},
	weekFn: function(e) { //选中返回星期
		console.log('返回星期')
		if (e.detail) {
			var newweek = this.data.weeks
			//去除原来选项
			for (var j = 0; j < newweek.length; j++) {
				newweek[j].checked = false;
			}
			var arr = ''
			for (var i = 0; i < e.detail.length; i++) {
				for (var k = 0; k < newweek.length; k++) {
					if (e.detail[i] == newweek[k].teacherId) {
						newweek[k].checked = true;
						if (i == e.detail.length - 1) {
							arr += newweek[k].teacherName;

						} else {
							arr += newweek[k].teacherName + '、';
						};
					};
				}
			}
			this.setData({
				week: arr,
				selweek: false,
				weekArr: e.detail,
				weeks: newweek
			})
		} else {
			this.setData({
				selweek: false
			})
		}

	},
	formSubmit: function(e) { //保存课程
		console.log(e)
		var that = this;
		this.setData({
			disabled: false
		})
		var savedata = e.detail.value;
		for (var key in savedata) {
			if (key == 'coursePeopleId') {
				savedata[key] = this.data.allpickers.coursePeople[this.data.coursePeopleIdx].coursePeopleId
			} else if (key == 'courseBaseId') {
				savedata[key] = this.data.allpickers.courseBase[this.data.courseBaseIdx].courseBaseId
			} else if (key == 'courseMain') {
				console.log('来到保存')
				console.log(this.data.allcourseMain)
				console.log(this.data.typeIndex)
				savedata['courseSub'] = this.data.allcourseMain[this.data.typeIndex[0]].sub[this.data.typeIndex[1]].courseSubId
				savedata['courseMainId'] = this.data.allcourseMain[this.data.typeIndex[0]].courseMainId
			}
		}
		for (var i = 0; i < this.data.allteacher.length; i++) {
			delete this.data.allteacher[i].checked
		}
		var coursePoints = []
		for (var i = 0; i < this.data.coursePoints.length; i++) {
			if (this.data.coursePoints[i].checked) {
				delete this.data.coursePoints[i].checked
				coursePoints.push(this.data.coursePoints[i])
			};
		}
		savedata['courseTeachers'] = this.data.teacherArr
		savedata['courseLogo'] = this.data.coverImgId
		savedata['courseImages'] = this.data.classImages
		savedata['coursePoint'] = coursePoints
		savedata['schoolId'] = this.data.schoolId
		if (this.data.courseId !== 0) {
			savedata['courseId'] = this.data.courseId
		};
		savedata['week'] = this.data.weekArr
		console.log(savedata)
		var loginInfo = loginFn();
		for (var key in loginInfo) {
			savedata[key] = loginInfo[key]
		}
		wx.request({
			url: urls.courseSave,
			method: 'POST',
			data: savedata,
			success: function(res) {
				console.log(res)
				if (res.data.code == '0') {
					wx.showToast({
						title: '提交成功',
					});
					that.setData({
						canEdit: true
					})
					wx.navigateBack({
						delta: 1
					})

				} else {
					that.setData({
						disabled: false
					})
					wx.showToast({
						title: res.data.info,
					})
				}
			}
		})
	},
	editFn: function(options) { //编辑课程
		//编辑课程
		if (options.courseId) {
			var myInfo = loginFn()
			var that = this;
			myInfo['courseId'] = options.courseId
			wx.request({
				url: urls.courseInfo+"?isTui=1",
				data: myInfo,
				success: function(res) {
					if (res.data.code == '0') {
						var courseInfo = res.data.data;
						var typeIndex = [] //课程类别
						var courseBaseIdx = 0 //适用基础
						var teachers = '' //上课老师
						var week = '' //星期
						var coursePeopleIdx = 0 //上课人数
						var coursePoint = [] //课程特点
						var coursePointTxt = '' //课程特点字符串
						var classImg = [] //课程图片
						var classImages = [] //课程图片id
						console.log(courseInfo)

						console.log(that.data.allcourseMain)
						for (var j = 0; j < that.data.allcourseMain.length; j++) {
							if (that.data.allcourseMain[j].courseMainId == courseInfo.courseMainId) {
								typeIndex[0] = j;
								for (var k = 0; k < that.data.allcourseMain[j].sub.length; k++) {
									if (that.data.allcourseMain[j].sub[k].courseSubId == courseInfo.courseSub) {
										typeIndex[1] = k
									};
								}
								break
							};
						}
						for (var k = 0; k < that.data.allpickers.courseBase.length; k++) {
							if (that.data.allpickers.courseBase[k].courseBaseId == courseInfo.courseBaseId) {
								courseBaseIdx = k
							};
						}
						for (var k = 0; k < that.data.allpickers.coursePeople.length; k++) {
							if (that.data.allpickers.coursePeople[k].coursePeopleId == courseInfo.coursePeopleId) {
								coursePeopleIdx = k
							};
						}
						if (courseInfo.courseTeachers) {
							for (var j = 0; j < courseInfo.courseTeachers.length; j++) {
								for (var k = 0; k < that.data.allteacher.length; k++) {
									if (that.data.allteacher[k].teacherId == courseInfo.courseTeachers[j].teacherId) {
										if (courseInfo.courseTeachers.length - 1 == j) {
											teachers += that.data.allteacher[k].teacherName
										} else {
											teachers += that.data.allteacher[k].teacherName + '、'
										};
										that.data.allteacher[k]['checked'] = true
									};
								}

							}
							that.setData({
								teachers: teachers,
								allteacher: that.data.allteacher,
							})
						};
						if (courseInfo.week) {
							for (var j = 0; j < courseInfo.week.length; j++) {
								for (var k = 0; k < that.data.weeks.length; k++) {
									if (that.data.weeks[k].teacherId == courseInfo.week[j]) {
										if (j == courseInfo.week.length - 1) {
											week += that.data.weeks[k].teacherName
										} else {
											week += that.data.weeks[k].teacherName + '、'
										}
										that.data.weeks[k]['checked'] = true
									};
								}

							}
							that.setData({
								week: week,
								weeks: that.data.weeks,
								weekArr: courseInfo.week
							})
						};
						if (courseInfo.coursePoint) {
							for (var j = 0; j < courseInfo.coursePoint.length; j++) {
								for (var k = 0; k < that.data.coursePoints.length; k++) {
									if (that.data.coursePoints[k].pointId == courseInfo.coursePoint[j].pointId) {
										if (j == courseInfo.coursePoint.length - 1) {
											coursePointTxt += that.data.coursePoints[k].pointName
										} else {
											coursePointTxt += that.data.coursePoints[k].pointName + '、'
										}
										that.data.coursePoints[k]['checked'] = true
									};
								}

							}
							that.setData({
								coursePointTxt: coursePointTxt,
								coursePoints: that.data.coursePoints,
							})
						};
						for (var i = 0; i < courseInfo.courseImages.length; i++) {
							classImages.push(courseInfo.courseImages[i].imageFileId)
							classImg.push(courseInfo.courseImages[i].img)
						}
						if (courseInfo.uploadImg) {
							that.setData({
								coverimg: courseInfo.uploadImg,
								coverImgId: courseInfo.courseLogo
							})
						};
						that.setData({
							schoolId: courseInfo.schoolId,
							schoolName: courseInfo.schoolName ? courseInfo.schoolName : that.data.schoolName,
							courseId: options.courseId,
							courseName: courseInfo.courseName,
							typeIndex: typeIndex,
							minAge: courseInfo.minAge,
							maxAge: courseInfo.maxAge,
							courseBaseIdx: courseBaseIdx,
							coursePeopleIdx: coursePeopleIdx,
							totalClassHours: courseInfo.totalClassHours,
							startTime: courseInfo.startTime,
							endTime: courseInfo.endTime,
							duration: courseInfo.duration,
							oldPrice: courseInfo.oldPrice,
							price: courseInfo.price,
							testClass: courseInfo.testClass,
							summary: courseInfo.summary,
							classImg: classImg,
							classImages: classImages,
						})
					};
				}
			})
		};
	},
	coursePointChange: function(e) { //选择课程特色
		this.setData({
			selcoursePoint: true
		})
	},
	coursePointFn: function(e) { //选择课程
		console.log(e)
		if (e.detail) {
			var coursePointTxt = ''
			for (var k = 0; k < this.data.coursePoints.length; k++) {
				this.data.coursePoints[k]['checked'] = false
			}
			for (var i = 0; i < e.detail.length; i++) {
				for (var k = 0; k < this.data.coursePoints.length; k++) {
					if (this.data.coursePoints[k].pointId == e.detail[i]) {
						if (i == e.detail.length - 1) {
							coursePointTxt += this.data.coursePoints[k].pointName
						} else {
							coursePointTxt += this.data.coursePoints[k].pointName + "、"
						}
						this.data.coursePoints[k]['checked'] = true
					};
				}
			}

			this.setData({
				selcoursePoint: false,
				coursePointTxt: coursePointTxt,
				coursePoints: this.data.coursePoints
			})
		} else {
			this.setData({
				selcoursePoint: false
			})
		}

	},
	closeimg: function(e) { //删除图片
		console.log(e)
		var insImgs = this.data.classImg
		var teacherImages = this.data.classImages
		insImgs.splice(e.currentTarget.dataset.idx, 1)
		teacherImages.splice(e.currentTarget.dataset.idx, 1)
		this.setData({
			classImg: insImgs,
			classImages: teacherImages
		})
	},
	approachasChange(e) {
		this.setData({
			approachaIdx: e.detail.value
		})
	},
	canEdit: function(e) { //编辑
		this.setData({
			canEdit: false,
			disabled: false
		})
	}
})
